package com.bsoft.gol.hcb.service.docteam.dao;

/**
 * @Author:FangZhiyi
 * @Description
 * @Data Created in 2020/7/15 9:49
 * @Moddified By:
 */

import com.bsoft.gol.hcb.utils.CommonUtils;
import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.spring.boot.annotation.SsdevDao;
import ctd.util.annotation.RpcService;
import ctd.util.converter.ConversionUtils;
import hcn.bean.qo.FindComplaintTeamListQo;
import hcn.bean.specialist.vo.QueryChronicDoctorListResponse;
import hcn.bean.specialist.vo.SatisfactionDoctorPushVo;
import hcn.docteam.DocTeamMemberEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.atag.dao.ext.HibernateExtendDAO;
import org.atag.dao.util.CustomAliasToEntityMapResultTransformer;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.transform.Transformers;

@SsdevDao(serviceId = "docTeamMemberDAOService")
public abstract class DocTeamMemberDAO extends HibernateExtendDAO<DocTeamMemberEntity> {
    public DocTeamMemberDAO() {
        this.setKeyField("medicalTeamMemberId");
    }

    @RpcService
    @DAOMethod(sql = " from DocTeamMemberEntity where medical_team_id in:teamIdList ")
    public abstract List<DocTeamMemberEntity> queryDocTeamMemberListByTeamIdList(@DAOParam("teamIdList") List<Long> teamIdList);

    @RpcService
    @DAOMethod(sql = " from DocTeamMemberEntity where doctor_id in:doctorIdList and medical_team_id in:teamIdList ")
    public abstract List<DocTeamMemberEntity> queryDoctorInfoByTeamIdList(@DAOParam("teamIdList") List<Long> teamIdList, @DAOParam("doctorIdList") List<String> doctorIdList);

    // TODO 为什么删了，还在引用？
    @DAOMethod(sql = " select medicalTeamId from DocTeamMemberEntity where doc_id=:docId and doctorId=:doctorId")
    public abstract List<Long> findMedicalTeamIdsByDoctorIdAndDocId(@DAOParam("docId") String docId, @DAOParam("doctorId") String doctorId);

    @RpcService
    @DAOMethod(sql = " from DocTeamMemberEntity where medical_team_id =:teamId ")
    public abstract List<DocTeamMemberEntity> queryDocTeamMemberList(@DAOParam("teamId") Long teamId);

    @DAOMethod(sql = " from DocTeamMemberEntity where medical_team_id =:teamId and role_id=1 and medical_team_member_id<>:memberId")
    public abstract DocTeamMemberEntity getOldCaptain(@DAOParam("teamId") Long teamId, @DAOParam("memberId") Long memberId);

    @RpcService
    @DAOMethod(sql = " from DocTeamMemberEntity where medicalTeamId in :teamIds and roleId=1 ")
    public abstract List<DocTeamMemberEntity> queryTeamLeaderMemberListByTeamIds(@DAOParam("teamIds") List<Long> teamIds);

    @RpcService
    @DAOMethod(sql = " select DISTINCT docId from DocTeamMemberEntity where medicalTeamId in :teamIds ")
    public abstract List<DocTeamMemberEntity> queryDoctorIdsByTeamIds(@DAOParam("teamIds") List<Long> teamIds);

    @DAOMethod(sql = " select 1 from DocTeamMemberEntity where medical_team_id =:teamId and  doc_id=:docId")
    public abstract Integer getCountByDoctorId(@DAOParam("docId") String docId, @DAOParam("teamId") Long medicalTeamId);

    @RpcService
    @DAOMethod(sql = " select medicalTeamId from DocTeamMemberEntity where doc_id=:docId")
    public abstract List<Long> findMedicalTeamIdsByDoctorId(@DAOParam("docId") String docId);

    @RpcService
    @DAOMethod(sql = " select medicalTeamId from DocTeamMemberEntity where doc_id=:docId and team_type=:teamType ")
    public abstract List<Long> findTeamIdsByDoctorIdAndType(@DAOParam("docId") String docId, @DAOParam("teamType") String teamType);

    @RpcService
    @DAOMethod(sql = " select medicalTeamId from DocTeamMemberEntity where doctorId=:doctorId")
    public abstract List<Long> findMedicalTeamIdList(@DAOParam("doctorId") String doctorId);

    @RpcService
//    @DAOMethod(sql = " select doctorName from DocTeamMemberEntity where medical_team_id =:teamId and  doctorId=:doctorId  ",limit = 0)
    public String getDoctorNameByDoctorId(@DAOParam("doctorId") String doctorId, @DAOParam("teamId") Long medicalTeamId) {
        DocTeamMemberEntity query = new DocTeamMemberEntity();
        query.setDoctorId(doctorId);
        query.setMedicalTeamId(medicalTeamId);

        DocTeamMemberEntity one = this.selectOneWithLimit(query, "");
        if (Objects.nonNull(one)) {
            return one.getDoctorName();
        }
        return null;

    }

    @DAOMethod(sql = "select b.organizationId from DocTeamMemberEntity a,DocTeamEntity b where a.medicalTeamId = b.medicalTeamId and a.docId =:docId ")
    public abstract List<String> queryOrganizationIdList(@DAOParam("docId") String docId);

    @RpcService
    @DAOMethod(sql = "SELECT a.medicalTeamId FROM DocTeamEntity a, DocTeamMemberEntity b WHERE a.medicalTeamId = b.medicalTeamId AND a.enableFlag=1 AND a.teamType=:teamType AND b.docId=:doctorId ")
    public abstract List<Long> findEnableTeamByDoctorId(@DAOParam("doctorId") String doctorId, @DAOParam("teamType") String teamType);

    @RpcService
    public List<QueryChronicDoctorListResponse> queryChronicDoctorList(final String docId, final List<Long> teamIdList) {

        HibernateStatelessResultAction<List<QueryChronicDoctorListResponse>> action = new AbstractHibernateStatelessResultAction<List<QueryChronicDoctorListResponse>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuffer sbf = new StringBuffer();
                sbf.append(" SELECT DISTINCT t.doc_id docId,t.doctor_id doctorId, t.doctor_name doctorName " +
                        "FROM doc_team_member t " +
                        "LEFT JOIN doc_team dt ON dt.medical_team_id = t.medical_team_id " +
                        "WHERE dt.enable_flag = 1 and t.medical_team_id in " +
                        "(SELECT medical_team_id FROM doc_team_member WHERE doc_id = :doc_id and medical_team_id in(:teamIdList)) ");

                Query query = ss.createSQLQuery(sbf.toString());
                query.setParameter("doc_id", docId);
                query.setParameterList("teamIdList", teamIdList);
                query.setResultTransformer(CustomAliasToEntityMapResultTransformer.INSTANCE);

                List<Map> list = query.list();
                List<QueryChronicDoctorListResponse> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, QueryChronicDoctorListResponse.class));
                    }
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();

    }


    @RpcService
    public List<SatisfactionDoctorPushVo> queryMedicalTeamDoctorList(final long medicalTeamId) {
        HibernateStatelessResultAction<List<SatisfactionDoctorPushVo>> action = new AbstractHibernateStatelessResultAction<List<SatisfactionDoctorPushVo>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuffer sql = new StringBuffer();
                sql.append("select t.medical_team_id as medicalTeamId ,t.organization_id as organizationId,");
                sql.append("t.department_id as departmentId,tm.doctor_id as doctorId ,tm.doctor_name as doctorName,tm.doc_id as docId ");
                sql.append("from doc_team t left join doc_team_member tm on t.medical_team_id=tm.medical_team_id ");
                sql.append("where tm.medical_team_id=:medicalTeamId ");
                Query query = ss.createSQLQuery(sql.toString());
                query.setParameter("medicalTeamId", medicalTeamId);
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<SatisfactionDoctorPushVo> teamDoctorList = new ArrayList<SatisfactionDoctorPushVo>();
                List<Map> list = query.list();
                if (list.size() > 0) {
                    for (Map map : list) {
                        teamDoctorList.add(ConversionUtils.convert(map, SatisfactionDoctorPushVo.class));
                    }
                    setResult(teamDoctorList);
                } else {
                    setResult(null);
                }
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    @RpcService
    public List<SatisfactionDoctorPushVo> findEnableTeamDocList(String teamType) {
        HibernateStatelessResultAction<List<SatisfactionDoctorPushVo>> action = new AbstractHibernateStatelessResultAction<List<SatisfactionDoctorPushVo>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuffer sql = new StringBuffer();
                sql.append(" SELECT b.doc_id as docId, b.doctor_name as doctorName, b.doctor_id as doctorId, a.organization_id as organizationId ");
                sql.append(" FROM doc_team a, doc_team_member b WHERE a.medical_team_id = b.medical_team_id ");
                sql.append(" AND a.enable_flag=1 AND a.team_type=:teamType GROUP BY b.doc_id ");
                Query query = ss.createSQLQuery(sql.toString());
                query.setParameter("teamType", teamType);
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<SatisfactionDoctorPushVo> teamDoctorList = new ArrayList<SatisfactionDoctorPushVo>();
                List<Map> list = query.list();
                if (list.size() > 0) {
                    for (Map map : list) {
                        teamDoctorList.add(ConversionUtils.convert(map, SatisfactionDoctorPushVo.class));
                    }
                    setResult(teamDoctorList);
                } else {
                    setResult(null);
                }
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    @RpcService
    public List<String> findComplaintTeamList(FindComplaintTeamListQo qo) {
        HibernateStatelessResultAction<List<String>> action = new AbstractHibernateStatelessResultAction<List<String>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuffer sql = new StringBuffer();
                sql.append(" SELECT DISTINCT a.organization_id as organizationId  FROM doc_team a left join doc_team_member b on a.medical_team_id = b.medical_team_id " +
                        " where 1=1 and a.enable_flag = 1 ");
                if (CommonUtils.isNotEmpty(qo.getTeamType())) {
                    sql.append(" and a.team_type =:teamType ");
                }
                if (CommonUtils.isNotEmpty(qo.getDoctorId())) {
                    sql.append(" and b.doc_id =:doctorId ");
                }
                if (CommonUtils.isNotEmpty(qo.getRoleId())) {
                    sql.append(" and b.role_id <=:roleId ");
                }
                if (CommonUtils.isNotEmpty(qo.getOrganizationIdList())) {
                    sql.append(" and a.organization_id in(:organizationIdList) ");
                }
                Query query = ss.createSQLQuery(sql.toString());
                if (CommonUtils.isNotEmpty(qo.getTeamType())) {
                    query.setParameter("teamType", qo.getTeamType());
                }
                if (CommonUtils.isNotEmpty(qo.getDoctorId())) {
                    query.setParameter("doctorId", qo.getDoctorId());
                }
                if (CommonUtils.isNotEmpty(qo.getRoleId())) {
                    query.setParameter("roleId", qo.getRoleId());
                }
                if (CommonUtils.isNotEmpty(qo.getOrganizationIdList())) {
                    query.setParameterList("organizationIdList", qo.getOrganizationIdList());
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<String> orgList = new ArrayList();
                List<Map> list = query.list();
                if (list.size() > 0) {
                    for (Map map : list) {
                        Object organizationId = map.get("organizationId");
                        if (CommonUtils.isNotEmpty(organizationId)) {
                            orgList.add(String.valueOf(organizationId));
                        }
                    }
                    setResult(orgList);
                } else {
                    setResult(null);
                }
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }
}
